package com.jindy.module.returnapplyorder.service.impl;

import com.jindy.common.core.domain.entity.SysUser;
import com.jindy.common.exception.base.BaseException;
import com.jindy.common.utils.DateUtils;
import com.jindy.common.utils.SecurityUtils;
import com.jindy.jpush.domain.UniPushDomain;
import com.jindy.jpush.utils.UniJpushUtils;
import com.jindy.module.approvalConfig.domain.ApprovalConfig;
import com.jindy.module.approvalConfig.mapper.ApprovalConfigMapper;
import com.jindy.module.constant.StatusConstants;
import com.jindy.module.jpush.mapper.JpushMapper;
import com.jindy.module.logisticscost.service.impl.LogisticsCostServiceImpl;
import com.jindy.module.order.domain.Order;
import com.jindy.module.order.domain.OrderProduct;
import com.jindy.module.order.mapper.OrderMapper;
import com.jindy.module.order.mapper.OrderProductMapper;
import com.jindy.module.outboundorder.mapper.OutboundOrderMachineMapper;
import com.jindy.module.returnapplyorder.domain.ReturnApply;
import com.jindy.module.returnapplyorder.domain.ReturnApplyProduct;
import com.jindy.module.returnapplyorder.dto.ReturnApplyDto;
import com.jindy.module.returnapplyorder.mapper.ReturnApplyMapper;
import com.jindy.module.returnapplyorder.mapper.ReturnApplyProductMapper;
import com.jindy.module.returnapplyorder.service.IReturnApplyService;
import com.jindy.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 回库申请单Service业务层处理
 *
 * @author ruoyi
 * @date 2022-10-19
 */
@Service
public class ReturnApplyServiceImpl implements IReturnApplyService {
    private static final Logger LOGGER = LoggerFactory.getLogger(LogisticsCostServiceImpl.class);
    @Autowired
    private ReturnApplyMapper returnApplyMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ReturnApplyProductMapper returnApplyProductMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderProductMapper orderProductMapper;

    @Autowired
    private OutboundOrderMachineMapper outboundOrderMachineMapper;

    /**
     * 配置表
     */
    @Resource
    private ApprovalConfigMapper approvalConfigMapper;

    /**
     * 消息推送设备信息表
     */
    @Resource
    private JpushMapper jpushMapper;


    /**
     * 查询回库申请单
     *
     * @param id 回库申请单主键
     * @return 回库申请单
     */
    @Override
    public ReturnApply selectReturnApplyById(Long id) {
        ReturnApply returnApply = returnApplyMapper.selectReturnApplyById(id);
        ReturnApplyProduct orderProduct = new ReturnApplyProduct();
        orderProduct.setReturnApplyId(returnApply.getId());
        List<ReturnApplyProduct> productList = returnApplyProductMapper.selectReturnApplyProductList(orderProduct);
        returnApply.setProductList(productList);
        return returnApply;
    }

    /**
     * 查询回库申请单列表
     *
     * @param returnApply 回库申请单
     * @return 回库申请单
     */
    @Override
    public List<ReturnApplyDto> selectReturnApplyList(ReturnApply returnApply) {
        returnApply.setParentId(0L);
        List<ReturnApplyDto> list = returnApplyMapper.selectReturnApplyList(returnApply);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(or -> {
                ReturnApplyProduct orderProduct = new ReturnApplyProduct();
                orderProduct.setReturnApplyId(or.getId());
                List<ReturnApplyProduct> productList = returnApplyProductMapper.selectReturnApplyProductList(orderProduct);
                or.setProductList(productList);

                // 查询子申请单
                List<ReturnApplyDto> outboundOrderList = returnApplyMapper.selectChileReturnApplyDtoList(or);
                or.setChildReturnApply(outboundOrderList);

                if (!CollectionUtils.isEmpty(outboundOrderList)) {
                    outboundOrderList.forEach(child -> {
                        // 查询子列表的产品列表
                        ReturnApplyProduct childOrderProduct = new ReturnApplyProduct();
                        childOrderProduct.setReturnApplyId(child.getId());
                        List<ReturnApplyProduct> childProductList = returnApplyProductMapper.selectReturnApplyProductList(childOrderProduct);
                        child.setProductList(childProductList);
                    });
                }
            });
        }
        return list;
    }

    /**
     * 查询回库申请子单列表
     *
     * @param returnApply 回库申请单
     * @return 回库申请单
     */
    @Override
    public List<ReturnApplyDto> childList(ReturnApply returnApply) {
        List<ReturnApplyDto> list = returnApplyMapper.childList(returnApply);
        List<Map<String, Object>> mlist = outboundOrderMachineMapper.selectMachineListByorderId(returnApply.getOrderId());
        System.out.println(mlist.size() + "======================================" + returnApply.getOrderId());
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(or -> {
                ReturnApplyProduct orderProduct = new ReturnApplyProduct();
                orderProduct.setReturnApplyId(or.getId());
                List<ReturnApplyProduct> productList = returnApplyProductMapper.selectReturnApplyProductList(orderProduct);
                or.setProductList(productList);
                or.setMachineList(mlist);// 订单id:orderId
            });
        }
        return list;
    }

    /**
     * 新增回库申请单
     *
     * @param returnApply 回库申请单
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertReturnApply(ReturnApply returnApply) {
        returnApply.setCreateTime(DateUtils.getNowDate());
        SysUser sysUser = sysUserService.selectUserByUserName(SecurityUtils.getUsername());
        returnApply.setCreateBy(sysUser.getUserName());
        returnApply.setCreateTime(DateUtils.getNowDate());
        returnApply.setSponsor(sysUser.getUserId());
        returnApply.setSponsorName(sysUser.getUserName());
        returnApply.setOrderStatus(StatusConstants.ApprovalStatusConstant.approvalStatus_1);
        // 如果新增的是父单直接赋2，新增的是子单则赋2的同时给父单赋2
        if (returnApply.getParentId().equals(0L)) {
            returnApply.setExpensesStatus("2");
        } else {
            returnApply.setExpensesStatus("2");
            Long id = returnApply.getParentId();
            ReturnApply returnApply1 = returnApplyMapper.selectReturnApplyById(id);
            returnApply1.setExpensesStatus("2");
            returnApplyMapper.updateReturnApply(returnApply1);
        }

        int result = returnApplyMapper.insertReturnApply(returnApply);
        //修改订单状态
        updateOrderStatus(returnApply);
        // 通知物流人员：王秋月
        noticeLogisticsPersonnel(returnApply.getOrderNo());
        return result;
    }

    /**
     * 修改租赁订单状态
     * @param returnApply
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderStatus(ReturnApply returnApply) {
        if (!CollectionUtils.isEmpty(returnApply.getProductList())) {
            // 关联产品
            returnApply.getProductList().forEach(applyOrderProduct -> {
                applyOrderProduct.setReturnApplyId(returnApply.getId());
            });
            returnApplyProductMapper.insertReturnApplyProducts(returnApply.getProductList());

            // 将产品回申请库数量放入订单产品表
            updateProduct(returnApply, returnApply.getProductList());

            // 判断订单回库申请是否完成
            Integer quantity = orderProductMapper.getQuantityCount(returnApply.getOrderId());
            Integer returnQuantity = returnApplyProductMapper.getReturnQuantityCount(returnApply.getOrderId());
            if (returnQuantity != null && returnQuantity.intValue() == quantity.intValue()) {
                // 申请回货数量和订单数量一致，修改回库申请单的状态为已提交
                ReturnApply parent = returnApplyMapper.selectReturnApplyById(returnApply.getParentId());
                parent.setOrderStatus(StatusConstants.ApprovalStatusConstant.approvalStatus_2);
                returnApplyMapper.updateReturnApply(parent);
                // 修改订单状态为入库申请完毕
                Order order1 = orderMapper.selectOrderById(returnApply.getOrderId());
                order1.setOrderStatus(StatusConstants.OrderStatusConstant.orderStatus_3);
                orderMapper.updateOrder(order1);
            } else {
                // 机器入库申请中的机器数量没申请完，修改租赁销售订单状态为入库申请中
                Order order2 = orderMapper.selectOrderById(returnApply.getOrderId());
                order2.setOrderStatus(StatusConstants.OrderStatusConstant.orderStatus_9);
                orderMapper.updateOrder(order2);
            }
        }
    }

    /**
     * 通知物流人员
     */
    private void noticeLogisticsPersonnel(String orderNo) {
        try {
            List<ApprovalConfig> approvalConfigList = approvalConfigMapper.selectApprovalConfigList(new ApprovalConfig("WLRY", "1"));
            if (CollectionUtils.isEmpty(approvalConfigList)) {
                throw new BaseException("请检查审批配置信息：WLRY");
            }
            List<String> registrationIdsByUserIds = jpushMapper.selectRegistrationIdsByUserIds(approvalConfigList.stream().map(ApprovalConfig::getUserId).collect(Collectors.toList()));
            if (CollectionUtils.isEmpty(registrationIdsByUserIds)){
                throw new BaseException("新建回库申请-物流人员设备id不存在");
            }
            UniJpushUtils.doPost(new UniPushDomain(registrationIdsByUserIds,"湿云",orderNo+"订单，新增回库申请完成"));
        } catch (Exception e) {
            LOGGER.error("新建回库申请-通知物流人员失败", e);
        }
    }

    /**
     * 将产品回申请库数量放入订单产品表
     */
    void updateProduct(ReturnApply returnApply, List<ReturnApplyProduct> applyProductList) {
        applyProductList.forEach(applyProduct -> {
            applyProduct.setReturnApplyId(returnApply.getId());
            OrderProduct orderProduct = new OrderProduct();
            orderProduct.setOrderId(returnApply.getOrderId());
            // orderProduct.setProductId(applyProduct.getProductId());
            orderProduct.setModel(applyProduct.getModel());
            List<OrderProduct> orderProducts = orderProductMapper.selectOrderProductList(orderProduct);
            if (!CollectionUtils.isEmpty(orderProducts)) {
                orderProduct = orderProducts.get(0);
                if (applyProduct.getReturnQuantity() != null) {
                    OrderProduct orderProduct1 = new OrderProduct();
                    orderProduct1.setId(orderProduct.getId());
                    orderProduct1.setReturnApplyQuantity(applyProduct.getReturnQuantity() + orderProduct.getReturnApplyQuantity());
                    orderProductMapper.updateOrderProduct(orderProduct1);
                }
            }

        });
    }

    /**
     * 修改回库申请单
     *
     * @param returnApply 回库申请单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateReturnApply(ReturnApply returnApply) {
        SysUser sysUser = sysUserService.selectUserByUserName(SecurityUtils.getUsername());
        returnApply.setUpdateBy(sysUser.getUserName());
        returnApply.setUpdateTime(DateUtils.getNowDate());
        // 删除订单关联的产品
        returnApplyProductMapper.deleteOrderProductByOrderId(returnApply.getId());
        // 修改订单状态
        updateOrderStatus(returnApply);
        return returnApplyMapper.updateReturnApply(returnApply);
    }

    /**
     * 批量删除回库申请单
     *
     * @param ids 需要删除的回库申请单主键
     * @return 结果
     */
    @Override
    public int deleteReturnApplyByIds(String[] ids) {
        return returnApplyMapper.deleteReturnApplyByIds(ids);
    }

    /**
     * 删除回库申请单信息
     *
     * @param id 回库申请单主键
     * @return 结果
     */
    @Override
    public int deleteReturnApplyById(String id) {
        return returnApplyMapper.deleteReturnApplyById(id);
    }

    @Override
    public ReturnApply getNo(ReturnApply order) {
        order.setParentId(0L);
        List<ReturnApplyDto> list = returnApplyMapper.selectReturnApplyList(order);
        if (!CollectionUtils.isEmpty(list)) {
            ReturnApplyDto returnApplyDto = list.get(0);
            ReturnApply now = new ReturnApply();
            now.setParentId(returnApplyDto.getId());
            Integer no = returnApplyMapper.getMaxNo(returnApplyDto);
            if (no == null) {
                no = 1;
            } else {
                no = no + 1;
            }
            now.setReturnApplyNo(returnApplyDto.getReturnApplyNo() + "-" + no);
            return now;
        }
        return null;
    }

    /**
     * 根据回库申请编号查询
     *
     * @param
     * @return
     */
    @Override
    public List<ReturnApply> getByReturnNo(String[] returnNo) {
        return returnApplyMapper.getByReturnNo(returnNo);
    }


}
